package org.abadirou.cdebacker.flst;

import java.util.Calendar;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import org.abadirou.cdebacker.flst.api.Chambre;
import org.abadirou.cdebacker.flst.api.Personne;
import org.abadirou.cdebacker.flst.api.Reservation;
import org.abadirou.cdebacker.flst.api.dao.ChambreDao;
import org.abadirou.cdebacker.flst.api.dao.PersonneDao;
import org.abadirou.cdebacker.flst.api.dao.ReservationDao;
import org.abadirou.cdebacker.flst.entity.ReservationImpl;
import org.joda.time.DateTime;

import com.google.inject.Inject;
import com.google.inject.Singleton;

@SuppressWarnings("unchecked")
@Singleton
public class JPAReservationDao implements ReservationDao {

	@Inject
	private EntityManager em;

	@Inject
	PersonneDao personneDao;

	@Inject
	ChambreDao chambreDao;

	@Override
	public Reservation createReservation(Personne personne, Chambre chambre,
			DateTime dateTime, DateTime dateTime2) {
		return new ReservationImpl(personneDao.get(personne.getId()),
				chambreDao.get(chambre.getId()), dateTime, dateTime2);
	}

	@Override
	public void saveEntry(Reservation reservation) {
		EntityTransaction tx = em.getTransaction();

		tx.begin();
		em.persist(reservation);
		tx.commit();
	}

	@Override
	public List<Reservation> getReservationByPersonne(Personne personne) {
		Query query = em
				.createNamedQuery(ReservationImpl.RESERVATION_BY_PERSONNE);

		return query.setParameter("personne", personne).getResultList();
	}

	@Override
	public List<Reservation> getReservationByChambre(Chambre chambre) {
		Query query = em
				.createNamedQuery(ReservationImpl.RESERVATION_BY_CHAMBRE);

		return query.setParameter("chambre", chambre).getResultList();
	}

	@Override
	public List<Reservation> getAllReservation() {
		return em.createNamedQuery(ReservationImpl.ALL_RESERVATION)
				.getResultList();
	}

	@Override
	public List<Reservation> getReservationByChambreByPeriod(DateTime from,
			DateTime to) {
		Query query = em
				.createNamedQuery(ReservationImpl.RESERVATION_BY_PERIOD);
		return query.setParameter("from", dateTimeToCal(from))
				.setParameter("to", dateTimeToCal(to)).getResultList();
	}

	@Override
	public List<Reservation> getReservationByChambreNow(DateTime now) {
		Query query = em.createNamedQuery(ReservationImpl.RESERVATION_NOW);
		return query.setParameter("now", dateTimeToCal(now)).getResultList();
	}

	private Calendar dateTimeToCal(DateTime date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date.toDate());
		return cal;
	}

}
